use std::{borrow::BorrowMut, ops::DerefMut};

use model_graph_types::container::process::{Process, ProcessManager, ProcessOptions};

pub struct SimpleProcessManager {}

#[async_trait::async_trait]
impl ProcessManager for SimpleProcessManager {
    async fn query(&self, identifier: &String) -> anyhow::Result<i32> {
        Ok(1)
    }

    async fn start(&self, identifier: &String, options: &ProcessOptions) -> anyhow::Result<u32> {
        //
        match options {
            ProcessOptions::Command(cmd_options) => {
                crate::process::command::start(identifier, cmd_options).await
            }
            _ => Err(anyhow::anyhow!("不支持的类型!")),
        }
    }

    async fn stop(&self, identifier: &String) -> anyhow::Result<i32> {
        //终止线程
        let cache_result = crate::process::RUNNING_PROCESSES
            .write()
            .map_err(|err| anyhow::anyhow!("获取锁失败:{}", err));

        match cache_result {
            Ok(mut cache) => {
                if let Some((process, mut handle, Some(child_arc))) = cache.remove(identifier) {
                    // let mut t = arc_process
                    //     .lock()
                    //     .map_err(|err| anyhow::anyhow!("获取锁失败:{}", err))?;
                    let mut child = child_arc.lock().map_err(|err| anyhow::anyhow!("{}", err))?;
                    let rs = child.kill();

                    tracing::debug!("关闭进程:{}", rs.is_ok());
                }
                Ok(0)
            }
            Err(_) => {
                tracing::error!("获取进程失败!");
                Err(anyhow::anyhow!("关闭进程中获取进程失败!"))
            }
        }
    }
}
